package net.ix.player;

import java.util.List;
import java.util.Map;

import net.ix.api.SongList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

public class Main extends Activity {
	private static String tag = "Main";
	
	private List<Map<String, Object>> list;
	private ProgressDialog progDialog;
	private MediaPlayer mp;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.main);
		startLoad();
	}
	private final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			progDialog.hide();
			setList();
		}
	};
	private final class TestThread extends HandlerThread {
		public TestThread(String name) {
			super(name);
		}
		protected void onLooperPrepared(){
			SongList slist = new SongList();
			list = slist.getList();
			handler.sendEmptyMessage(0);
		}
	}
	private void startLoad(){
		progDialog = ProgressDialog.show(Main.this, "", "正在读取列表...", true);
		new TestThread("SongList").start();
	}
	private void setList(){
		mp = new MediaPlayer();
		ListView listView = (ListView)findViewById(R.id.songList);
		SimpleAdapter adapter = new SimpleAdapter(this,list,R.layout.item,
				new String[]{"name"},
				new int[]{R.id.songName});
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(itemClick);
	}
	private OnItemClickListener itemClick = new OnItemClickListener(){
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			Toast.makeText(getApplicationContext(), (String)list.get(position).get("url"), Toast.LENGTH_SHORT).show();
			Uri uri = Uri.parse((String)list.get(position).get("url"));
			mp.setOnBufferingUpdateListener(new OnBufferingUpdateListener(){
				@Override
				public void onBufferingUpdate(MediaPlayer arg0, int percent) {
					Log.i(tag, percent+"");
				}
			});
			mp.create(Main.this, uri);
			//mp.start();
		}
	};
}
